package pers.hxy.lookweather.view.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.ArrayList;
import java.util.List;

import pers.hxy.lookweather.R;
import pers.hxy.lookweather.utils.SpUtil;
import pers.hxy.lookweather.utils.StringUtil;

/**
 * 保存常用城市，只能选择国内的城市，配合SelectCityActivity
 */
public class SaveCityActivity extends AppCompatActivity {
    private static final String SP_KEY = "saved-cities";
    private ImageView ivBack;
    private ImageView ivAdd;
    private ListView lvCity;
    private List<City> cities;
    private CityAdapter adapter;
    private ActivityResultLauncher launcherGetLocation;
    private int longClickPosition; // 通过长按某一项可以删除该城市

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_save_city);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        ivBack = findViewById(R.id.iv_save_city_back);
        ivAdd = findViewById(R.id.iv_add_common_city);
        lvCity = findViewById(R.id.lv_common_city);
        cities = getSavedCities();
        adapter = new CityAdapter(SaveCityActivity.this, R.layout.activity_save_city, cities);
        lvCity.setAdapter(adapter);

        launcherGetLocation = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                o -> {
                    if (o.getResultCode() == RESULT_OK && o.getData() != null) {
                        String location_id = o.getData().getStringExtra(WeatherActivity.INTENT_KEY_LOCATION_ID);
                        String location_name = o.getData().getStringExtra(WeatherActivity.INTENT_KEY_LOCATION_NAME);
                        if (StringUtil.isNotNullOrEmpty(location_id) && StringUtil.isNotNullOrEmpty(location_name)) {
                            addCity(new City(location_id, location_name));
                        }
                    }
                });

        ivBack.setOnClickListener(v -> {
            setResult(RESULT_CANCELED);
            finish();
        });

        ivAdd.setOnClickListener(v -> {
            launcherGetLocation.launch(new Intent(this, SelectCityActivity.class));
        });

        // 单击某一项表示选择该城市
        lvCity.setOnItemClickListener((parent, view, position, id) -> {
            selectCity(cities.get(position));
        });

        registerForContextMenu(lvCity);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        adapter = null;
    }

    @NonNull
    private List<City> getSavedCities() {
        String s = SpUtil.getString(getApplicationContext(), SP_KEY);
        List<City> cityList = new ArrayList<>();
        if (s != null && !s.isEmpty()) {
            for (String c : s.split(";")) {
                cityList.add(new City(c));
            }
        }
        return cityList;
    }

    private void saveCities() {
        String[] s = new String[cities.size()];
        for (int i = 0; i < cities.size(); i++) {
            s[i] = cities.get(i).toString();
        }
        // 用';'分割不同城市，读取时用';'分割就可以了
        SpUtil.putString(getApplicationContext(), SP_KEY, String.join(";", s));
    }

    private void addCity(City city) {
        cities.add(city);
        saveCities();
        adapter.notifyDataSetChanged();
//        lvCity.setAdapter(adapter);
    }

    private void delCity() {
        if (0 <= longClickPosition && longClickPosition < cities.size()) {
            cities.remove(longClickPosition);
            saveCities();
//            lvCity.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
    }

    private void selectCity(City city) {
        Intent intent = new Intent();
        intent.putExtra(WeatherActivity.INTENT_KEY_LOCATION_ID, city.getId());
        intent.putExtra(WeatherActivity.INTENT_KEY_LOCATION_NAME, city.getName());
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        longClickPosition = info.position;
        // 长按某一项会弹出菜单，可以选择删除该项或选择该项
        menu.add(0, 0, 0, "删除");
        menu.add(0, 1, 0, "选择");
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case 0:
                delCity();
                break;
            case 1:
                selectCity(cities.get(longClickPosition));
                break;
            default:
                break;
        }
        return true;
    }
}



class City {
    String id;
    String name;

    public City(String id, String name) {
        this.id = id;
        this.name = name;
    }

    // 约定用“:”分割id和name，方便读取和保存城市信息
    public City(String s) {
        int i = s.indexOf(':');
        id = s.substring(0, i);
        name = s.substring(i + 1);
    }

    @NonNull
    @Override
    public String toString() {
        return id + ":" + name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}



class CityAdapter extends ArrayAdapter<City> {

    public CityAdapter(@NonNull Context context, int resource, @NonNull List<City> objects) {
        super(context, resource, objects);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        City city = getItem(position);
        ViewHolder viewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_save_city, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.tvCityName = convertView.findViewById(R.id.tv_item_save_city);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.tvCityName.setText(city.getName());
        return convertView;
    }

    private static class ViewHolder {
        TextView tvCityName;
    }
}